<template>
  <div
    ref="chartRef"
    class="e-chart"
    :style="{ width: width + 'px', height: height + 'px' }"
  ></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: Number,
    default: 400
  },
  height: {
    type: Number,
    default: 300
  }
})

const chartRef = ref(null)
const chartInstance = ref(null)

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return

  if (chartInstance.value) {
    chartInstance.value.dispose()
  }

  // 创建图表实例
  chartInstance.value = echarts.init(chartRef.value)
  chartInstance.value.setOption(props.option)
}

// resize 处理（防抖）
let resizeTimer = null
const handleResize = () => {
  if (resizeTimer) clearTimeout(resizeTimer)
  resizeTimer = setTimeout(() => {
    if (chartInstance.value) {
      chartInstance.value.resize()
    }
  }, 100)
}

// 监听 option 变化
watch(() => props.option, (newOption) => {
  if (chartInstance.value && newOption) {
    chartInstance.value.setOption(newOption)
  }
}, { deep: true })

// 监听尺寸变化
watch(() => [props.width, props.height], handleResize)

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
  if (resizeTimer) clearTimeout(resizeTimer)
})
</script>

<style scoped>
.e-chart {
  /* 不要设置其他样式，让父容器控制 */
}
</style>
